/*
 * commons is a based project implemented
 * Copyright (C) 2024 Jasmine
 */
package com.commons.uid.worker;

import java.util.Objects;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.commons.uid.props.WorkerNodeProperty;
import com.commons.uid.utils.DockerUtils;
import com.commons.uid.utils.NetUtils;
import com.commons.uid.worker.entity.WorkerNodeEntity;

/**
 * Represents an implementation of {@link WorkerIdAssigner}, the worker id will be discarded after assigned to the
 * UidGenerator
 *
 * @author yutianbao
 */
@Component
public class DisposableWorkerIdAssigner implements WorkerIdAssigner {

    private static final Logger LOGGER = LoggerFactory.getLogger(DisposableWorkerIdAssigner.class);

    @Autowired
    private WorkerNodeProperty workerNodeProperty;

    /**
     * Assign worker id base on database.
     * <p>
     * If there is host name & port in the environment, we considered that the node runs in Docker container<br>
     * Otherwise, the node runs on an actual machine.
     *
     * @return assigned worker id
     */
    @Override
    public long assignWorkerId() {
        // build worker node entity
        WorkerNodeEntity workerNodeEntity = buildWorkerNode();
        LOGGER.info("Add worker node:" + workerNodeEntity);
        return workerNodeEntity.getId();
    }

    /**
     * Build worker node entity by IP and PORT
     */
    private WorkerNodeEntity buildWorkerNode() {
        WorkerNodeEntity workerNodeEntity = new WorkerNodeEntity();
        Long id = workerNodeProperty.getWorkerId();
        if (Objects.isNull(id)) {
            workerNodeEntity.setId(RandomUtils.nextInt(0, 100000));
        } else {
            workerNodeEntity.setId(id);
        }
        if (DockerUtils.isDocker()) {
            workerNodeEntity.setType(WorkerNodeType.CONTAINER.value());
            workerNodeEntity.setHostName(DockerUtils.getDockerHost());
            workerNodeEntity.setPort(DockerUtils.getDockerPort());
        } else {
            workerNodeEntity.setType(WorkerNodeType.ACTUAL.value());
            workerNodeEntity.setHostName(NetUtils.getLocalAddress());
            workerNodeEntity.setPort(System.currentTimeMillis() + "-" + RandomUtils.nextInt(0, 100000));
        }
        return workerNodeEntity;
    }
}
